package com.zry.pda.ui.activity.print

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import com.google.zxing.common.BitmapUtils
import com.jq.printer.JQPrinter
import com.jq.printer.Printer_define
import com.jq.printer.jpl.Barcode
import com.jq.printer.jpl.JPL
import com.jq.printer.jpl.Page
import com.jq.printer.jpl.Text
import com.jq.ui.BtConfigActivity
import com.zry.pda.R
import com.zry.pda.been.FlowCodeDetailData
import com.zry.pda.been.FlowCodeInfoBean
import com.zry.pda.databinding.ActivityGenerateRqcodeBinding
import com.zry.pda.ui.base.BaseActivity
import com.zry.pda.utils.SpUtil
import com.zry.pda.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_generate_rqcode.*
import kotlinx.android.synthetic.main.common_title.*


/**
 * @author zry
 */
class GenerateRqCodeActivity : BaseActivity() {
    private var generateRqCodeBinding: ActivityGenerateRqcodeBinding? = null

    private var bluetoothAdapter: BluetoothAdapter? = null
    private val mBtOpenSilent = true
    private var jQPrinter: JQPrinter? = JQPrinter(Printer_define.PRINTER_MODEL.JLP351)
    private var blueToothAddress: String? = null
    private var mBtDevNameAddress: String? = null
    private var generatePrintStr = "true"


    private val mReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: android.content.Context, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED == action) {
                if (jQPrinter != null) {
                    if (jQPrinter!!.isOpen) {
                        jQPrinter!!.close()
                    }
                }
                Toast.makeText(context, "蓝牙连接已断开", Toast.LENGTH_SHORT).show()
            }
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_generate_rqcode
    }

    override fun initData() {
        generateRqCodeBinding = viewDataBinding as ActivityGenerateRqcodeBinding

        initTitleView()
        //打开蓝牙
        openBluetooth()
        initView()

        getIntentData()
    }


    private fun initTitleView() {

        titleCenterText.text = getString(R.string.printCode)
        commonLeftLinearLayout.setOnClickListener {
            val intent = Intent(this, com.zry.pda.MainActivity::class.java)
            startActivity(intent)
            finish()
        }
        titleRightText.setText(R.string.switchText)
        commonRightLinearLayout.setOnClickListener {
            //选择打印机
            selectPrint()
        }

        generatePrintQRCode.setOnClickListener {
            val codeBtn = generatePrintQRCode.text.toString().trim()
            ToastUtil.toast(this, codeBtn)
            if (codeBtn == "打印完成") {
                exit()
                val intent = Intent(this, com.zry.pda.MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                if (generatePrintStr == "true") {
                    //开始打印
                    startPrint()
                } else if (generatePrintStr == "false") {
                    //选择打印机
                    selectPrint()
                }
            }
        }
    }

    private fun initView() {

        mBtDevNameAddress = SpUtil().getString(this, "blueToothAddress")
        if ((mBtDevNameAddress != null) and ("" != mBtDevNameAddress)) {
            blueToothAddressLin.visibility = View.VISIBLE
            blueToothAddressTV.text = mBtDevNameAddress
            generatePrintStr = "true"
            if (bluetoothAdapter!!.isDiscovering) {
                bluetoothAdapter!!.cancelDiscovery()
            }
            if (jQPrinter != null) {
                jQPrinter!!.close()
            }
            if (!jQPrinter!!.open(mBtDevNameAddress)) {
                Toast.makeText(this, "打印机打开失败", Toast.LENGTH_SHORT).show()
                generatePrintStr = "false"
                return
            }
            if (!jQPrinter!!.wakeUp()) {
                generatePrintQRCode.text = "打印"
                return
            }
            myApplication!!.printer = jQPrinter!!
            Log.e("JQ", "printer open ok")

            val filter = IntentFilter()
            //蓝牙断开
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
            registerReceiver(mReceiver, filter)
        } else {
            generatePrintStr = "false"
        }
    }

    /**
     * 选择打印机
     */
    private fun selectPrint() {
        if (bluetoothAdapter == null) {
            return
        }
        val myIntent = Intent(this@GenerateRqCodeActivity, BtUiConfigActivity::class.java)
        startActivityForResult(myIntent, REQUEST_BT_ADDR)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_BT_ENABLE) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show()
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "不允许蓝牙开启", Toast.LENGTH_SHORT).show()
                return
            }
        } else if (requestCode == REQUEST_BT_ADDR) {
            if (resultCode == Activity.RESULT_OK) {
                blueToothAddress = data!!.getStringExtra(BtConfigActivity.EXTRA_BLUETOOTH_DEVICE_ADDRESS)
                //                mBtDevName=data.getStringExtra(BtConfigActivity.EXTRA_BLUETOOTH_DEVICE_NAME);
                SpUtil().putString(this@GenerateRqCodeActivity, "blueToothAddress", blueToothAddress!!)
                //                SpUtil.putString(GenerateRqCodeActivity.this, "mBtDevName", blueToothAddress);

                if (blueToothAddress != null) {
                    blueToothAddressLin.visibility = View.VISIBLE
                    blueToothAddressTV.text = blueToothAddress
                    if (bluetoothAdapter!!.isDiscovering) {
                        bluetoothAdapter!!.cancelDiscovery()
                    }
                    if (jQPrinter != null) {
                        jQPrinter!!.close()
                    }
                    if (!jQPrinter!!.open(blueToothAddress)) {
                        Toast.makeText(this, "打印机打开失败", Toast.LENGTH_SHORT).show()
                        generatePrintStr = "false"
                        return
                    }
                    if (!jQPrinter!!.wakeUp()) {
                        generatePrintQRCode.text = "打印"
                        return
                    }
                    myApplication!!.printer = jQPrinter!!
                    Log.e("JQ", "printer open ok")

                    val filter = IntentFilter()
                    //蓝牙断开
                    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
                    registerReceiver(mReceiver, filter)
                    //开始打印
                    startPrint()
                }
            } else {
                generatePrintQRCode.text = "打印"
            }
        }
    }


    /**
     * 打开蓝牙
     */
    private fun openBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "本机没有找到蓝牙硬件或驱动！", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        myApplication!!.btAdapter = bluetoothAdapter!!

        // 如果本地蓝牙没有开启，则开启
        //以下操作需要在AndroidManifest.xml中注册权限android.permission.BLUETOOTH ；android.permission.BLUETOOTH_ADMIN
        if (!bluetoothAdapter!!.isEnabled) {
            Toast.makeText(this, "正在开启蓝牙", Toast.LENGTH_SHORT).show()
            if (!mBtOpenSilent) {
                // 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择，比如用户单击了Yes开启，
                // 那么将会收到RESULT_OK的结果，
                // 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
                val mIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(mIntent, REQUEST_BT_ENABLE)
            } else { // 用enable()方法来开启，无需询问用户(无声息的开启蓝牙设备),这时就需要用到android.permission.BLUETOOTH_ADMIN权限。
                bluetoothAdapter!!.enable()
                Toast.makeText(this, "本地蓝牙已打开", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "本地蓝牙已打开", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 开始打印
     */
    private fun startPrint() {
        // Cancel discovery because it will slow down the connection
        if (bluetoothAdapter!!.isDiscovering) {
            bluetoothAdapter!!.cancelDiscovery()
        }
        if (!jQPrinter!!.waitBluetoothOn(5000)) {
            Toast.makeText(this, "蓝牙未打开,请先与打印机配对后重试!", Toast.LENGTH_SHORT).show()
            return
        }
        if (!jQPrinter!!.isOpen) {
            Toast.makeText(this, "打印机未被打开,请先与打印机配对后重试!", Toast.LENGTH_SHORT).show()
            return
        }
        //开始打印
        generatePrintQRCode.text = "打印中"
        generatePrintQRCode.isEnabled = false
        enforcementPrintButton_click()
        return
    }

    private fun getQRCodeString(flowCode: String, number: Int): String {
        var flowCodeStr = flowCode
        for (i in 0 until number) {
            flowCodeStr += " "
        }
        return flowCodeStr
    }


    private var flowCodeInfoBeanList: MutableList<FlowCodeInfoBean>? = null
    private var productName: String? = null
    private var dataList: ArrayList<FlowCodeDetailData>? = null

    private fun getIntentData() {
        productName = intent.getStringExtra("productName")
        dataList = intent.getSerializableExtra("DataList") as ArrayList<FlowCodeDetailData>

        flowCodeInfoBeanList = mutableListOf()

        dataList!!.forEach { flowCodeDetailData ->

            flowCodeInfoBeanList!!.add(FlowCodeInfoBean(productName!!, flowCodeDetailData.Code, flowCodeDetailData.CodeDuan,
                    flowCodeDetailData.TraceList[0].CodeID, flowCodeDetailData.TraceList[flowCodeDetailData.TraceList.size-1].CodeID
            ))
        }

        generateTitleText.text = flowCodeInfoBeanList!![0].productName
        generateCirculationCode.text = flowCodeInfoBeanList!![0].flowCode
        generateCirculationCodeStart.text = flowCodeInfoBeanList!![0].flowChildMinCode
        generateCirculationCodeLase.text = flowCodeInfoBeanList!![0].flowChildMaxCode


        try {
            val bitmap: Bitmap = BitmapUtils.create2DCode(flowCodeInfoBeanList!![0].flowShortCode)//根据内容生成二维码
            generatePrintQRCodeImg.setImageBitmap(bitmap)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 打印
     *
     * @return
     */
    private fun printExpress(): Boolean {
        jQPrinter!!.jpl.intoGPL(1200)
        if (!jQPrinter!!.jpLsupport) {
            Toast.makeText(this, "不支持JPL，请设置正确的打印机型号！", Toast.LENGTH_SHORT).show()
            return false
        }
        val jpl = jQPrinter!!.jpl
        val textLeft = 250
        val fontSize = 20
        val lineSize = 30
        val titleSize = 25
        val tileLineSize = 36

        flowCodeInfoBeanList!!.forEachIndexed { index, flowCodeInfoBean ->
            if (!jpl.page.start(0, 0, 700, 500, Page.PAGE_ROTATE.x0)) {
                return false
            }
            var y = 30
            var y1 = 130
            if (!jpl.text.drawOut(Printer_define.ALIGN.CENTER, 0, 650, y, flowCodeInfoBean.productName, 52, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)) {
                return false
            }
            y += 110
            if (!jpl.barcode.QRCode(50, y, 0, Barcode.QRCODE_ECC.LEVEL_M, Barcode.BAR_UNIT.x4, JPL.ROTATE.x0, getQRCodeString(flowCodeInfoBean.flowShortCode, 180))) {
                return false
            }
            jpl.text.drawOut(textLeft, y1, "流通码：", titleSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)
            y1 += tileLineSize
            jpl.text.drawOut(textLeft, y1, flowCodeInfoBean.flowCode, fontSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0);

            y1 += lineSize
            jpl.text.drawOut(textLeft, y1, "追溯码号段：", titleSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)
            y1 += tileLineSize
            jpl.text.drawOut(textLeft, y1, flowCodeInfoBean.flowChildMinCode, fontSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)
            y1 += lineSize
            jpl.text.drawOut(textLeft + 50, y1, "------", fontSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)
            y1 += lineSize
            jpl.text.drawOut(textLeft, y1, flowCodeInfoBean.flowChildMaxCode, fontSize, false, false, false, false, Text.TEXT_ENLARGE.x1, Text.TEXT_ENLARGE.x1, JPL.ROTATE.x0)

            jpl.page.end()
            jpl.page.print()
        }

        return jQPrinter!!.jpl.exitGPL(1000)
    }

    /**
     * 真正打印代码
     */
    private fun enforcementPrintButton_click() {
        if (jQPrinter == null) {
            Log.e("JQ", "printer null")
            return
        }
        printExpress()
        var i: Int = 0
        try {
            Thread.sleep(5000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        while (i < 10) {
            //超时时间过短也会造成获取状态失败，此超时时间和打印机内容多少有关。
            if (!jQPrinter!!.getPrinterState(3000)) {
                //Toast.makeText(this, "获取打印机状态失败", Toast.LENGTH_SHORT).show();
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

                i++
                continue
            }
            if (jQPrinter!!.isCoverOpen) {
                Toast.makeText(this, "打印机纸仓盖未关闭", Toast.LENGTH_SHORT).show()
                return
            } else if (jQPrinter!!.isNoPaper) {
                Toast.makeText(this, "打印机缺纸", Toast.LENGTH_SHORT).show()
                return
            }
            //表示打印结束
            if (!jQPrinter!!.isPrinting) {
                Toast.makeText(this, "打印结束", Toast.LENGTH_SHORT).show()
                printOver()
                break
            } else {
                try {
                    Thread.sleep(500)
                } catch (e: InterruptedException) {
                }

            }//否则等待500ms,并继续获取状态
            i++
        }
        if (i == 10) {
            Toast.makeText(this, "打印出错", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 打印结束
     */
    private fun printOver() {
        generatePrintQRCode.text = "打印完成"
        generatePrintQRCode.isEnabled = true
    }


    //退出时关闭蓝牙，关闭打印机
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            exit()
            val intent = Intent(this, com.zry.pda.MainActivity::class.java)
            startActivity(intent)
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (jQPrinter != null) {
            if (!jQPrinter!!.close()) {
                Toast.makeText(this, "打印机关闭失败", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "打印机关闭成功", Toast.LENGTH_SHORT).show()
            }
            jQPrinter = null
        }
        if (bluetoothAdapter != null) {
            if (bluetoothAdapter!!.isEnabled) {
                bluetoothAdapter!!.disable()
                Toast.makeText(this, "关闭蓝牙成功", Toast.LENGTH_LONG).show()
            }
        }
    }

    companion object {

        /**
         * 打印相关
         */
        private val REQUEST_BT_ENABLE = 0
        private val REQUEST_BT_ADDR = 1
    }


}
